<?php
namespace app\admin\controller;

use think\Controller;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Request;
use think\facade\View;

use app\common\model\EmptyController as EmptyControllerModel;
use app\common\model\Fields as FieldsModel;
use app\common\model\Category as CategoryModel;
use app\common\model\Module as ModuleModel;
use app\common\model\Classify as ClassifyModel;

class EmptyController extends Base
{

    protected $prefix;
    protected $database;

    function initialize()
    {
        //$this->common();
        $this->prefix = config('database.connections.mysql.prefix');//表前缀
        $this->database = config('database.connections.mysql.database');//数据库名

    }

    //栏目列表
	public function list(){
        $catid = input('param.catid','');
        $siteid = $this->admin_siteid;//站点id

        $tablename = CONTROLLER_NAME;//当前控制器名称
        $database = DATABASE;//数据库名
        $prefix = PREFIX;//表前缀

        //在数据库中查表是否存在
        $sql = "select table_name from information_schema.tables where table_schema='" . $database . "' and table_name='" . $prefix . $tablename . "'";
        $biao = DB::query($sql);
        if (!$biao) {
            $name = $tablename . '表在数据库中不存在';
            $this->error($name, url('admin/index/main'));
        }

        //搜索
        $map = [];
        $param = input("param.");
        if(isset($param['title']) && $param['title'] != ''){
            $map[] = ['title','like','%'.$param['title'].'%'];
        }

        if(isset($param['cate_id']) && $param['cate_id'] != ''){
            $map[] = ['catids','find in set',$param['cate_id']];
        }

        if(isset($param['moduleid']) && $param['moduleid'] != ''){
            $map[] = ['moduleid','=',$param['moduleid']];
        }

        if(isset($param['classifyid']) && $param['classifyid'] != ''){
            $map[] = ['classifyid','=',$param['classifyid']];
        }



        //所有打开的模型选择
        $ModuleModel = new ModuleModel();
        $module_list = $ModuleModel -> where("status","=",1)
            ->order("orderid asc")
            ->select();
        View::assign('module_list', $module_list);

        if ($catid) {
            $cat_res = DB::name('category')->where('id', $catid)->find();
            View::assign('title', $cat_res['catname']);
            View::assign('catid', $catid);
            View::assign('module', $cat_res['module']);//模型、数据库名
            //详细内容
            //$res = DB::name($cat_res['module'])->where('catid', $catid)->where('siteid', $siteid)->order('orderid desc')->select();
            $res = DB::name($cat_res['module'])->where($map)->where('catid', $catid)->where('siteid', $siteid)->order('orderid asc,id desc')->paginate([
                'list_rows'=> 10,//每页数量
                'query' => request()->param(),
            ])->each(function($item, $key){
                if(isset($item['catids'])) {
                    $c_list = DB::name('category')->where('id', 'in', $item['catids'])->select()->toArray();
                    $cate_names = '';
                    foreach ($c_list as $k => $v) {
                        $cate_names .= "(".$v['id'].")".$v['catname'] . "(".count(explode(',',$v['arrparentid']))."级)" . '，';
                    }
                    $item['cate_names'] = trim($cate_names, "，");

                    /*if(isset($item['classifyid']) && $item['classifyid'] != 0){
                        $classify_one = DB::name('classify')->where('id', '=', $item['classifyid'])->find();
                        $item['classifyid'] = $classify_one['title']."(classifyid:".$classify_one['id'].")";
                    }else{
                        $item['classifyid'] = '';
                    }*/
                }
                return $item;
            });
            $page = $res->render();
            $total = $res->total();
            View::assign('total', $total);
            View::assign('page', $page);
            View::assign('res', $res);

            $moduleid = $cat_res['moduleid'];
            $ModuleModel = new ModuleModel();
            $module_one = $ModuleModel -> where("id","=",$moduleid)->find();
            //单章
            if ($module_one['emptytable'] == 2) {
                //所有字段
                $arr_field = DB::name('fields')->where('moduleid', $moduleid)->where('status', 1)->order('orderid asc')->select()->toArray();
                //dump($arr_field);
                //整理 setup 字段
                $EmptyControllerModel = new EmptyControllerModel();
                $arr_field = $EmptyControllerModel->arrange_fields($arr_field);
                View::assign('arr_field', $arr_field);
                //数据遍历
                $table_res = DB::name($cat_res['module'])->where('catid', $catid)->find();
                //数据处理(表单字段的数据显示)
                if ($table_res) {
                    $table_res = $EmptyControllerModel->table_data($table_res, $cat_res['moduleid']);
                }
                View::assign('table_res', $table_res);
                return View::fetch('empty/page');
            } else {
                //字段遍历(表格显示is_table=1)
                $FieldsModel = new FieldsModel();
                $fields_res = $FieldsModel ->getModuleFields($cat_res['moduleid']);
                View::assign('fields_res', $fields_res);
                return View::fetch('empty/index');
            }
        } else {
            $mod = DB::name('module')->where('name', $tablename)->find();

            View::assign('title', $mod['title']);
            View::assign('module', $mod['name']);//模型、数据库名

            $res = DB::name($tablename)
                ->where($map)
                ->where('siteid', $siteid)->order('orderid asc,id desc')->paginate([
                    'list_rows'=> 10,//每页数量
                    'query' => request()->param(),
                ])
                ->each(function($item, $key){
                    if(isset($item['catids'])) {
                        $c_list = DB::name('category')->where('id', 'in', $item['catids'])->select()->toArray();
                        $cate_names = '';
                        foreach ($c_list as $k => $v) {
                            $cate_names .= "(".$v['id'].")".$v['catname']. "(".count(explode(',',$v['arrparentid']))."级)" . '，';
                        }
                        $item['cate_names'] = trim($cate_names, "，");
                    }

//                    if(isset($item['classifyid']) && $item['classifyid'] != 0){
//                        $classify_one = DB::name('classify')->where('id', '=', $item['classifyid'])->find();
//                        $item['classifyid'] = $classify_one['title']."(classifyid:".$classify_one['id'].")";
//                    }else{
//                        $item['classifyid'] = '';
//                    }

                    return $item;
                });
            $page = $res->render();
            $total = $res->total();

            View::assign('total', $total);
            View::assign('page', $page);
            View::assign('res', $res);

            //字段遍历(表格显示is_table=1)
            $FieldsModel = new FieldsModel();
            $fields_res = $FieldsModel ->getModuleFields($mod['id']);
            View::assign('fields_res', $fields_res);

            //该模型下的分类
//            $ClassifyModel = new ClassifyModel();
//            $classify_list = $ClassifyModel ->getClassifyListBymoduleid($mod['id']);
//            View::assign('classify_list', $classify_list);

            return View::fetch('empty/index');
        }
	}

	//单页添加和修改
    public function page(){
        $data = input('post.');
        unset($data['file']);
        $catid = $data['catid'];

        $cat_res = DB::name('category')->where('id',$catid)->find();
        $moduleid = $cat_res['moduleid'];
        //所有字段
        $fields = DB::name('field')->field('field,type,setup')->where('moduleid',$moduleid)->select();
        //字段处理(添加和修改时)
        $EmptyControllerModel = new EmptyControllerModel();
        $newDate = $EmptyControllerModel->add_edit_arrange_fields($fields,$data);
        //用以判断是新增还是修改
        $res_one = DB::name($cat_res['module'])->where('catid',$catid)->find();

        if($res_one){
            $res = DB::name($cat_res['module'])->where('catid',$catid)->update($newDate);
        }else{
            $res = DB::name($cat_res['module'])->insert($newDate);
        }
        if(!$res){
            return dyajaxReturn(0, '操作失败');
        }
        return dyajaxReturn(1, '操作成功',(string)url('category/index'));
    }

	//添加
	public function add(){

        $prefix = $this->prefix;//表前缀
        $database = $this->database;//数据库名

		if(request()->isPost()){
			$data = input('post.');
			//加入站点id
            $data['siteid'] = $this->admin_siteid;
            unset($data['file']);
            unset($data['dypic']);
            unset($data['dyvideo']);
            unset($data['select']);

            if(isset($data['catid']) && $data['catid']!= '') {
                $catid = $data['catid'];
                $cat = DB::name('category')->where('id', $catid)->find();
                $moduleid = $cat['moduleid'];
                $mod = DB::name('module')->where('id',"=",$moduleid)->find();
                $url = url($cat['module'].'/list',array('catid'=>$catid));
                $tablename = $cat['module'];
            }else{
                $request = Request::instance();
                $tablename = strtolower($request->controller());
                $mod = DB::name('module')->where('name',$tablename)->find();
                $moduleid = $mod['id'];
                $url = url($mod['name'].'/list');
            }

            //所有字段
            $fields = DB::name('fields')->field('field,type,setup')
                ->where("status","=",1)
                ->where("is_form","=",1)
                ->where('moduleid',$moduleid)->select();
            //字段处理(添加和修改时)
            $EmptyControllerModel = new EmptyControllerModel();
            $newDate = $EmptyControllerModel->add_edit_arrange_fields($fields,$data);
            $newDate['orderid'] = GetOrderID($tablename);
            if(!isset($newDate['add_time']) || $newDate['add_time'] ==''){
                $newDate['add_time'] = time();
            }
            //classify表的模型id查询
            /*if($tablename == 'classify'){
                $ModuleModel = new ModuleModel();
                $module_one = $ModuleModel -> where("id","=",$newDate['moduleid'])->find();
                $newDate['module_name'] = $module_one['title'];
            }*/

            if(isset($newDate['catids'])){
                $newDate['catids'] = trim($newDate['catids']);
            }
            $id = DB::name($tablename)->insertGetId($newDate);
            if(!$id){
                return dyajaxReturn(0, '添加失败');
            }
            adminLog($mod['title'].'的添加',$id);
            return dyajaxReturn(1, '添加成功','',(string)$url);
		}else {
            $catid = input('param.catid');

            //栏目管理
            if($catid) {
                $cat_res = DB::name('category')->where('id', $catid)->find();

                View::assign('title', $cat_res['catname'] . '-添加');
                View::assign('catid', $catid);
                View::assign('module', $cat_res['module']);
                View::assign('url', url($cat_res['module'] . '/index',array('catid'=>$catid)));

                $moduleid = $cat_res['moduleid'];
            }else{
            //网站功能
                $request = Request::instance();
                $tablename = strtolower($request->controller());
                //在数据库中查表是否存在
                $sql = "select table_name from information_schema.tables where table_schema='".$database."' and table_name='".$prefix.$tablename."'";
                $biao =  DB::query($sql);
                if(!$biao){
                    $name = $tablename.'表在数据库中不存在';
                    $this->error($name,url('admin/index/main'));
                }
                $mod = DB::name('module')->where('name',$tablename)->find();

                View::assign('title', $mod['title']. '-添加');
                View::assign('module', $mod['name']);//模型、数据库名
                View::assign('url', url($tablename . '/index',array('catid'=>$catid)) );

                $moduleid = $mod['id'];
            }
            //所有字段
            $arr_field = DB::name('fields')->where('moduleid',$moduleid)->where('status',1)->order('orderid asc')->select()->toArray();

            //整理 setup 字段
            $EmptyControllerModel = new EmptyControllerModel();
            $arr_field =  $EmptyControllerModel ->arrange_fields($arr_field);
            View::assign('arr_field',$arr_field);


            //所有打开的模型选择
            $ModuleModel = new ModuleModel();
            $module_list = $ModuleModel -> where("status","=",1)
                ->order("orderid asc")
                ->select();
            View::assign('module_list', $module_list);

            /*//该模型下的分类
            $ClassifyModel = new ClassifyModel();
            $classify_list = $ClassifyModel ->getClassifyListBymoduleid($moduleid);
            View::assign('classify_list', $classify_list);*/

            return View::fetch('empty/form');
        }
	}

	//修改
    public function edit(){

        $prefix = $this->prefix;//表前缀
        $database = $this->database;//数据库名

        $EmptyControllerModel = new EmptyControllerModel();

        if(request()->isPost()){
            $data = input('post.');
            $data['siteid'] = $this->admin_siteid;
            unset($data['file']);
            unset($data['dypic']);
            unset($data['dyvideo']);
            unset($data['select']);

            $catid= '';
            if(isset($data['catid'])){
                $catid = $data['catid'];
                unset($data['catid']);
            }

            $id = $data['id'];
            unset($data['id']);

            if($catid){
                $cat = DB::name('category')->where('id', $catid)->find();
                $moduleid = $cat['moduleid'];
                $mod = DB::name('module')->where('id',"=",$moduleid)->find();
                $url = url($cat['module'].'/list',array('catid'=>$catid));
                $tablename = $cat['module'];
            }else{
                $request = Request::instance();
                $tablename = strtolower($request->controller());
                $mod = DB::name('module')->where('name',$tablename)->find();
                $moduleid = $mod['id'];
                $url = url($mod['name'].'/list');
            }
            //$cat = DB::name('category')->where('id',$catid)->find();
            //所有字段
            //$moduleid = $cat['moduleid'];
            $fields = DB::name('fields')
                ->field('field,type,setup')
                ->where("status","=",1)
                ->where("is_form","=",1)
                ->where('moduleid',$moduleid)->select();
            //字段处理(添加和修改时)
            $EmptyControllerModel = new EmptyControllerModel();
            $newDate = $EmptyControllerModel->add_edit_arrange_fields($fields,$data);
            if(!isset($newDate['update_time']) || $newDate['update_time'] ==''){
                $newDate['update_time'] = time();
            }

            /*//classify表的模型id查询
            if($tablename == 'classify'){
                $ModuleModel = new ModuleModel();
                $module_one = $ModuleModel -> where("id","=",$newDate['moduleid'])->find();
                $newDate['module_name'] = $module_one['title'];
            }*/

            if(isset($newDate['catids'])){
                $newDate['catids'] = trim($newDate['catids']);
            }

            $res = DB::name($tablename)->where('id',$id)->update($newDate);
            if(!$res){
                return dyajaxReturn(0, '修改失败');
            }
            adminLog($mod['title'].'的修改',$id);
            return dyajaxReturn(1, '修改成功','',(String)$url);
        }else {
            $catid = input('param.catid');

            if($catid) {
                $cat_res = DB::name('category')->where('id', $catid)->find();
                View::assign('title', $cat_res['catname']. '-修改');
                View::assign('catid', $catid);
                View::assign('module', $cat_res['module']);
                View::assign('url', url($cat_res['module'] . '/index',array('catid'=>$catid)));

                $moduleid = $cat_res['moduleid'];
                $tablename = $cat_res['module'];

            }else{
                //网站功能
                $request = Request::instance();
                $tablename = strtolower($request->controller());
                //在数据库中查表是否存在
                $sql = "select table_name from information_schema.tables where table_schema='".$database."' and table_name='".$prefix.$tablename."'";
                $biao =  DB::query($sql);
                if(!$biao){
                    $name = $tablename.'表在数据库中不存在';
                    $this->error($name,url('admin/index/main'));
                }
                $mod = DB::name('module')->where('name',$tablename)->find();
                View::assign('title', $mod['title']. '-修改');
                View::assign('module', $mod['name']);
                View::assign('url', url($tablename . '/index',array('catid'=>$catid)));

                $moduleid = $mod['id'];
            }
            $id = input('param.id');
            $table_res = DB::name($tablename)->where('id',$id)->find();

            //数据处理(表单字段的数据显示)
            $table_res = $EmptyControllerModel->table_data($table_res,$moduleid);
            View::assign('table_res',$table_res);

            //获取栏目列表
            if(isset($table_res['catids'])) {
                $CategoryModel = new CategoryModel();
                $treeList = $CategoryModel->treeList([], true, [], $table_res['catids']);
                View::assign('treeList', $treeList);
            }
            //所有字段
            $arr_field = DB::name('fields')->where('moduleid',$moduleid)->where('status',1)->order('orderid asc')->select()->toArray();
            //整理 setup 字段
            $arr_field =  $EmptyControllerModel ->arrange_fields($arr_field,$table_res);

            //所有打开的模型选择
            $ModuleModel = new ModuleModel();
            $module_list = $ModuleModel -> where("status","=",1)
                ->order("orderid asc")
                ->select();
            View::assign('module_list', $module_list);

            /*//该模型下的分类
            $ClassifyModel = new ClassifyModel();
            $classify_list = $ClassifyModel ->getClassifyListBymoduleid($moduleid);
            View::assign('classify_list', $classify_list);*/

            View::assign('arr_field',$arr_field);
            return View::fetch('empty/form');
        }
    }


    //删除
    public function delete(){
        $param = input("param.");
        $table = $param['table'];
        $ids = $param['ids'];

        $res = DB::name($table)->where("id","in",$ids)->delete();
        if(!$res){
            return dyajaxReturn(0, '删除失败');
        }
        adminLog($table.'表的删除',$ids);
        return dyajaxReturn(1, '删除成功');
    }

}
